package com.xuanwei.rabbit_consume.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.xuanwei.dao.entity.*;
import com.xuanwei.dao.mapper.*;
import com.xuanwei.xwcommon.consts.ProjectUrl;
import com.xuanwei.xwcommon.entity.dto.*;
import com.xuanwei.xwcommon.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/6/28 13:36
 **/
@Component
@Slf4j
public class ProductHandler {

    private XwProductMapper productMapper;

    private XwProductParamMapper productParamMapper;

    private XwProductAttributeMapper productAttributeMapper;

    private XwProductAttributeValueMapper productAttributeValueMapper;

    private XwProductSkuMapper productSkuMapper;


    private RestTemplate restTemplate;

    public ProductHandler(XwProductMapper productMapper,
                          XwProductParamMapper productParamMapper,
                          XwProductAttributeMapper productAttributeMapper,
                          XwProductAttributeValueMapper productAttributeValueMapper,
                          XwProductSkuMapper productSkuMapper,
                          RestTemplate restTemplate) {
        this.productMapper = productMapper;
        this.productParamMapper = productParamMapper;
        this.productAttributeMapper = productAttributeMapper;
        this.productAttributeValueMapper = productAttributeValueMapper;
        this.productSkuMapper = productSkuMapper;
        this.restTemplate = restTemplate;
    }

    public void insert(Integer id) {
        ProductDto productDto = findById(id);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<ProductDto> formEntity = new HttpEntity<>(productDto, headers);
        try {
            log.info(JSON.toJSONString(productDto));
            ResponseEntity<R> rResponseEntity = restTemplate.postForEntity(ProjectUrl.SEARCH + "/es/add", formEntity, R.class);
            log.info(JSON.toJSONString(rResponseEntity));
        } catch (Exception e) {
            log.error("insert fail:{}", e);
        }
    }

    public void delete(Integer id) {
        try {
            Map<String, Integer> param = new HashMap<>();
            param.put("id", id);
            ResponseEntity<R> forEntity = restTemplate.getForEntity(ProjectUrl.SEARCH + "es/delete?id={id}", R.class, param);
            log.info(JSON.toJSONString(forEntity));
        } catch (Exception e) {
            log.error("delete fail:{}", e);
        }
    }

    /**
     * 根据ID查询商品相关信息
     *
     * @param id ID
     * @return 数据
     */
    private ProductDto findById(Integer id) {
        XwProduct product = productMapper.selectById(id);
        if (product == null) {
            log.warn("the product is not exists:{}", id);
            return null;
        }

        ProductDto productDto = new ProductDto();
        //商品基本信息
        BeanUtils.copyProperties(product, productDto);

        List<XwProductParam> productParams = productParamMapper.selectList(
                new QueryWrapper<XwProductParam>()
                        .select("id,param,value")
                        .eq("product_id", id));
        List<ProductParamDto> productParamDtos = BeanUtil.copyList(productParams, ProductParamDto.class);
        //商品参数
        productDto.setProductParams(productParamDtos);
        List<XwProductAttribute> productAttributes = productAttributeMapper.selectList(
                new QueryWrapper<XwProductAttribute>()
                        .select("id,name")
                        .eq("product_id", id));

        //商品规格
        List<ProductAttributeDto> productAttributeDtos = Lists.newArrayListWithCapacity(productAttributes.size());
        productAttributes.forEach(s -> {
            Integer attrId = s.getId();
            ProductAttributeDto productAttributeDto = new ProductAttributeDto();
            productAttributeDto.setId(attrId);
            productAttributeDto.setName(s.getName());
            List<XwProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectList(
                    new QueryWrapper<XwProductAttributeValue>()
                            .select("id,value,image_url")
                            .eq("product_attribute_id", s.getId()));
            List<ProductAttributeDto.AttributeValue> values = Lists.newArrayListWithCapacity(productAttributeValues.size());
            productAttributeValues.forEach(i -> {
                ProductAttributeDto.AttributeValue attributeValue = new ProductAttributeDto.AttributeValue();
                attributeValue.setId(i.getId());
                attributeValue.setName(i.getValue());
                attributeValue.setImage(i.getImageUrl());
                values.add(attributeValue);
            });
            productAttributeDto.setValues(values);
            productAttributeDtos.add(productAttributeDto);
        });
        productDto.setAttributes(productAttributeDtos);

        //商品规格详情
        List<XwProductSku> productSkus = productSkuMapper.selectList(
                new QueryWrapper<XwProductSku>()
                        .eq("product_id", id)
                        .eq("status", 0));
        List<ProductSkuDto> productSkuDtos = BeanUtil.copyList(productSkus, ProductSkuDto.class);
        productDto.setProductSku(productSkuDtos);
        return productDto;
    }
}
